package org.seckill.web;

import org.seckill.dao.cache.RedisDao;
import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.dto.SeckillResult;
import org.seckill.entity.Seckill;
import org.seckill.enums.SeckillStatEnum;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.CookieGenerator;
import org.springframework.web.util.WebUtils;

import java.util.Date;
import java.util.List;

/**
 * Created by zhangyijun on 15/11/4.
 */
@Controller//@Service @Component
@RequestMapping("/seckill")// url:/模块/资源/{id}/细分 /seckill/list
public class SeckillController implements InitializingBean {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    public static final String REDIS_KEY = "seckill:";

    @Autowired
    private SeckillService seckillService;
    @Autowired
    private RedisDao redisDao;
    @Autowired
    private AmqpTemplate amqpTemplate;

    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(Model model) {
        //获取列表页
        List<Seckill> list = seckillService.getSeckillList();
        model.addAttribute("list", list);
        //list.jsp + model = ModelAndView
        return "list";// /WEB-INF/jsp/"list".jsp
    }

    @RequestMapping(value = "/{seckillId}/detail", method = RequestMethod.GET)
    public String detail(@PathVariable("seckillId") Long seckillId, Model model) {
        if (seckillId == null) {
            return "redirect:/seckill/list";
        }
        Seckill seckill = seckillService.getById(seckillId);
        if (seckill == null) {
            return "forward:/seckill/list";
        }
        model.addAttribute("seckill", seckill);
        return "detail";
    }

    //ajax json
    @RequestMapping(value = "/{seckillId}/exposer",
            method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public SeckillResult<Exposer> exposer(@PathVariable Long seckillId) {
        SeckillResult<Exposer> result;
        try {
            Exposer exposer = seckillService.exportSeckillUrl(seckillId);
            result = new SeckillResult<Exposer>(true, exposer);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new SeckillResult<Exposer>(false, e.getMessage());
        }
        return result;
    }


    @Override
    public void afterPropertiesSet() throws Exception {
//        List<Seckill> goodsList = seckillService.listGoods();
//        if (goodsList != null && goodsList.size() > 0) {
//            for (Seckill seckill : goodsList) {
//                redisDao.set(REDIS_KEY + seckill.getSeckillId(), 3600, seckill.getNumber());
//            }
//        }
    }


    /**
     * qps
     * 245.9
     */
    @RequestMapping(value = "/{seckillId}/{md5}/execution",
            method = RequestMethod.POST,
            produces = {"application/json;charset=UTF-8"})
    @ResponseBody
    public SeckillResult<SeckillExecution> execute(@PathVariable("seckillId") Long seckillId,
                                                   @PathVariable("md5") String md5,
                                                   @RequestParam(value = "killPhone", required = true) Long phone) {
        //springmvc valid
        if (phone == null) {
            return new SeckillResult<SeckillExecution>(false, "未注册");
        }

        Long stockInRedis = redisDao.get(REDIS_KEY + seckillId, Long.class);

        if (stockInRedis == null) {
            Seckill stock = seckillService.getById(seckillId);
            if (stock == null || stock.getNumber() <= 0) {
                if (stock != null) {
                    redisDao.set(REDIS_KEY + seckillId, 3600, stock.getNumber());
                }
                return new SeckillResult<SeckillExecution>(false, "商品已抢完");
            }
        } else if (stockInRedis <= 0) {
            return new SeckillResult<SeckillExecution>(false, "商品已抢完");
        }

        SeckillResult<SeckillExecution> result;
        try {
            //存储过程调用.
            final SeckillExecution seckillExecution = seckillService.executeSeckillProcedure(seckillId, phone, md5);
            SeckillExecution execution = seckillExecution;
            return new SeckillResult<SeckillExecution>(true, execution);
        } catch (RepeatKillException e) {
            SeckillExecution execution = new SeckillExecution(seckillId, SeckillStatEnum.REPEAT_KILL);
            return new SeckillResult<SeckillExecution>(true, execution);
        } catch (SeckillCloseException e) {
            SeckillExecution execution = new SeckillExecution(seckillId, SeckillStatEnum.END);
            return new SeckillResult<SeckillExecution>(true, execution);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            SeckillExecution execution = new SeckillExecution(seckillId, SeckillStatEnum.INNER_ERROR);
            return new SeckillResult<SeckillExecution>(true, execution);
        }
    }

    @RequestMapping(value = "/mq", method = RequestMethod.GET)
    @ResponseBody
    public void time() {
        Date date = new Date();
        amqpTemplate.convertAndSend("发送时间：" + date);
        logger.info("11111111111111111111111111111111111111");
        logger.info("发送时间：{}",date);
    }


}
